Linq join update without creating new

111

Linq join update without creating new -

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Assert = Xunit.Assert;

namespace Research.Rli.Tests
{
    public class Appointment
    {
        public int Id { get; set; }
        public string Location { get; set; }
    }

    [TestClass]
    public class ResearchTester
    {
        [TestMethod]
        public void Should_update_appointments()
        {
            var appointments1 = new List<Appointment>
            {
                new Appointment { Id = 1, Location = "" },
                new Appointment { Id = 2, Location = "" },
                new Appointment { Id = 3, Location = "" }
            };

            var appointments2 = new List<Appointment>
            {
                new Appointment { Id = 1, Location = "My location 1" },
                new Appointment { Id = 3, Location = "My location 3" }
            };

            Func<Appointment, Appointment, Appointment> UpdateLocation
                = ((a, b) => { if (b != null) { a.Location = b.Location; } return a; });

            var updatedAppointmets =
            (
                from a1 in appointments1
                join a2 in appointments2 on a1.Id equals a2.Id into g
                from g1 in g.DefaultIfEmpty(null)
                select UpdateLocation(a1, g1)
            ).ToList();

            foreach (Appointment a in updatedAppointmets)
            {
                Console.WriteLine
                (
                    string.Format("Id [{0}] Location [{1}]", a.Id, a.Location)
                );
            }

            // Output:
            // Id [1] Location [My location 1]
            // Id [2] Location []
            // Id [3] Location [My location 3]
        }
    }
}

Comments

Submit
0 Comments